package cn.wokoba.service.activity.repository;


import cn.wokoba.dao.event.EventPublisher;
import cn.wokoba.dao.mapper.*;
import cn.wokoba.dao.pojo.*;
import cn.wokoba.dao.redis.RedissonService;
import cn.wokoba.service.activity.event.ActivitySkuStockZeroMessageEvent;
import cn.wokoba.service.activity.model.*;
import cn.wokoba.types.common.Constants;
import cn.wokoba.types.enums.ResponseCode;
import cn.wokoba.types.exception.AppException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Repository
@Slf4j
public class ActivityRepository {
    private final SimpleDateFormat dateFormatDay = new SimpleDateFormat("yyyy-MM-dd");
    private final static SimpleDateFormat dateFormatMonth = new SimpleDateFormat("yyyy-MM");
    @Autowired
    ActivitySkuStockZeroMessageEvent activitySkuStockZeroMessageEvent;
    @Autowired
    RedissonService redisService;
    @Autowired
    RaffleActivityMapper raffleActivityMapper;
    @Autowired
    UserRaffleOrderMapper userRaffleOrderMapper;
    @Autowired
    RaffleActivityAccountMapper raffleActivityAccountMapper;
    @Autowired
    RaffleActivityAccountDayMapper raffleActivityAccountDayMapper;
    @Autowired
    RaffleActivityAccountMonthMapper raffleActivityAccountMonthMapper;
    @Autowired
    RaffleActivitySkuMapper raffleActivitySkuMapper;
    @Autowired
    RaffleActivityCountMapper raffleActivityCountMapper;
    @Autowired
    TransactionTemplate transactionTemplate;

    @Autowired
    RaffleActivityOrderMapper raffleActivityOrderMapper;
    @Autowired
    RaffleActivityStageMapper raffleActivityStageMapper;
    @Autowired
    EventPublisher eventPublisher;


    public ActivityEntity queryRaffleActivityByActivityId(Long activityId) {
        // 优先从缓存获取
        String cacheKey = Constants.CacheKey.ACTIVITY_KEY + activityId;
        ActivityEntity activityEntity = redisService.getValue(cacheKey);
        if (null != activityEntity) return activityEntity;
        // 从库中获取数据
        RaffleActivity raffleActivity = raffleActivityMapper.selectOne(new LambdaQueryWrapper<RaffleActivity>()
                .eq(RaffleActivity::getActivityId, activityId));
        activityEntity = ActivityEntity.builder()
                .activityId(raffleActivity.getActivityId())
                .activityName(raffleActivity.getActivityName())
                .activityDesc(raffleActivity.getActivityDesc())
                .beginDateTime(raffleActivity.getBeginDateTime())
                .endDateTime(raffleActivity.getEndDateTime())
                .strategyId(raffleActivity.getStrategyId())
                .state(ActivityStateVO.valueOf(raffleActivity.getState()))
                .build();
        redisService.setValue(cacheKey, activityEntity);
        return activityEntity;
    }

    public UserRaffleOrderEntity queryNoUsedRaffleOrder(PartakeRaffleActivityEntity partakeRaffleActivityEntity) {
        // 查询数据

        UserRaffleOrder userRaffleOrderReq = new UserRaffleOrder();
        userRaffleOrderReq.setUserId(partakeRaffleActivityEntity.getUserId());
        userRaffleOrderReq.setActivityId(partakeRaffleActivityEntity.getActivityId());
        UserRaffleOrder userRaffleOrder = userRaffleOrderMapper.queryNoUsedRaffleOrder(userRaffleOrderReq);
        if (null == userRaffleOrder) return null;
        // 封装结果
        UserRaffleOrderEntity userRaffleOrderEntity = new UserRaffleOrderEntity();
        userRaffleOrderEntity.setUserId(userRaffleOrder.getUserId());
        userRaffleOrderEntity.setActivityId(userRaffleOrder.getActivityId());
        userRaffleOrderEntity.setActivityName(userRaffleOrder.getActivityName());
        userRaffleOrderEntity.setStrategyId(userRaffleOrder.getStrategyId());
        userRaffleOrderEntity.setOrderId(userRaffleOrder.getOrderId());
        userRaffleOrderEntity.setOrderTime(userRaffleOrder.getOrderTime());
        userRaffleOrderEntity.setOrderState(UserRaffleOrderStateVO.valueOf(userRaffleOrder.getOrderState()));
        return userRaffleOrderEntity;
    }

    public void saveCreatePartakeOrderAggregate(CreatePartakeOrderAggregate createPartakeOrderAggregate) {

        String userId = createPartakeOrderAggregate.getUserId();
        Long activityId = createPartakeOrderAggregate.getActivityId();
        ActivityAccountEntity activityAccountEntity = createPartakeOrderAggregate.getActivityAccountEntity();
        ActivityAccountMonthEntity activityAccountMonthEntity = createPartakeOrderAggregate.getActivityAccountMonthEntity();
        ActivityAccountDayEntity activityAccountDayEntity = createPartakeOrderAggregate.getActivityAccountDayEntity();
        UserRaffleOrderEntity userRaffleOrderEntity = createPartakeOrderAggregate.getUserRaffleOrderEntity();

        // 统一切换路由，以下事务内的所有操作，都走一个路由
        transactionTemplate.execute(status -> {
            try {
                // 1. 更新总账户
                int totalCount = raffleActivityAccountMapper.updateActivityAccountSubtractionQuota(
                        RaffleActivityAccount.builder()
                                .userId(userId)
                                .activityId(activityId)
                                .build());
                if (1 != totalCount) {
                    status.setRollbackOnly();
                    log.warn("写入创建参与活动记录，更新总账户额度不足，异常 userId: {} activityId: {}", userId, activityId);
                    throw new AppException(ResponseCode.ACCOUNT_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_QUOTA_ERROR.getInfo());
                }

                // 2. 创建或更新月账户，true - 存在则更新，false - 不存在则插入
                if (createPartakeOrderAggregate.isExistAccountMonth()) {
                    int updateMonthCount = raffleActivityAccountMonthMapper.updateActivityAccountMonthSubtractionQuota(
                            RaffleActivityAccountMonth.builder()
                                    .userId(userId)
                                    .activityId(activityId)
                                    .month(activityAccountMonthEntity.getMonth())
                                    .build());
                    if (1 != updateMonthCount) {
                        // 未更新成功则回滚
                        status.setRollbackOnly();
                        log.warn("写入创建参与活动记录，更新月账户额度不足，异常 userId: {} activityId: {} month: {}", userId, activityId, activityAccountMonthEntity.getMonth());
                        throw new AppException(ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getInfo());
                    }
                    // 更新总账户中月镜像库存
                    raffleActivityAccountMapper.updateActivityAccountMonthSubtractionQuota(
                            RaffleActivityAccount.builder()
                                    .userId(userId)
                                    .activityId(activityId)
                                    .build());
                } else {
                    raffleActivityAccountMonthMapper.insertActivityAccountMonth(RaffleActivityAccountMonth.builder()
                            .userId(activityAccountMonthEntity.getUserId())
                            .activityId(activityAccountMonthEntity.getActivityId())
                            .month(activityAccountMonthEntity.getMonth())
                            .monthCount(activityAccountMonthEntity.getMonthCount())
                            .monthCountSurplus(activityAccountMonthEntity.getMonthCountSurplus())
                            .build());
                    // 新创建月账户，则更新总账表中月镜像额度
                    raffleActivityAccountMapper.updateActivityAccountMonthSurplusImageQuota(RaffleActivityAccount.builder()
                            .userId(userId)
                            .activityId(activityId)
                            .monthCountSurplus(activityAccountEntity.getMonthCountSurplus())
                            .build());
                }

                // 3. 创建或更新日账户，true - 存在则更新，false - 不存在则插入
                if (createPartakeOrderAggregate.isExistAccountDay()) {
                    int updateDayCount = raffleActivityAccountDayMapper.updateActivityAccountDaySubtractionQuota(RaffleActivityAccountDay.builder()
                            .userId(userId)
                            .activityId(activityId)
                            .day(activityAccountDayEntity.getDay())
                            .build());
                    if (1 != updateDayCount) {
                        // 未更新成功则回滚
                        status.setRollbackOnly();
                        log.warn("写入创建参与活动记录，更新日账户额度不足，异常 userId: {} activityId: {} day: {}", userId, activityId, activityAccountDayEntity.getDay());
                        throw new AppException(ResponseCode.ACCOUNT_DAY_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_DAY_QUOTA_ERROR.getInfo());
                    }
                    // 更新总账户中日镜像库存
                    raffleActivityAccountMapper.updateActivityAccountDaySubtractionQuota(
                            RaffleActivityAccount.builder()
                                    .userId(userId)
                                    .activityId(activityId)
                                    .build());
                } else {
                    raffleActivityAccountDayMapper.insertActivityAccountDay(RaffleActivityAccountDay.builder()
                            .userId(activityAccountDayEntity.getUserId())
                            .activityId(activityAccountDayEntity.getActivityId())
                            .day(activityAccountDayEntity.getDay())
                            .dayCount(activityAccountDayEntity.getDayCount())
                            .dayCountSurplus(activityAccountDayEntity.getDayCountSurplus())
                            .build());
                    // 新创建日账户，则更新总账表中日镜像额度
                    raffleActivityAccountMapper.updateActivityAccountDaySurplusImageQuota(RaffleActivityAccount.builder()
                            .userId(userId)
                            .activityId(activityId)
                            .dayCountSurplus(activityAccountEntity.getDayCountSurplus())
                            .build());
                }

                // 4. 写入参与活动订单
                userRaffleOrderMapper.insert(UserRaffleOrder.builder()
                        .userId(userRaffleOrderEntity.getUserId())
                        .activityId(userRaffleOrderEntity.getActivityId())
                        .activityName(userRaffleOrderEntity.getActivityName())
                        .strategyId(userRaffleOrderEntity.getStrategyId())
                        .orderId(userRaffleOrderEntity.getOrderId())
                        .orderTime(userRaffleOrderEntity.getOrderTime())
                        .orderState(userRaffleOrderEntity.getOrderState().getCode())
                        .build());

                return 1;
            } catch (DuplicateKeyException e) {
                status.setRollbackOnly();
                log.error("写入创建参与活动记录，唯一索引冲突 userId: {} activityId: {}", userId, activityId, e);
                throw new AppException(ResponseCode.INDEX_DUP.getCode(), e);
            }
        });

    }

    public void saveCreatePartakeOrderAggregate(CreatePartakeOrderAggregate createPartakeOrderAggregate, int drawCount) {

        String userId = createPartakeOrderAggregate.getUserId();
        Long activityId = createPartakeOrderAggregate.getActivityId();
        ActivityAccountEntity activityAccountEntity = createPartakeOrderAggregate.getActivityAccountEntity();
        ActivityAccountMonthEntity activityAccountMonthEntity = createPartakeOrderAggregate.getActivityAccountMonthEntity();
        ActivityAccountDayEntity activityAccountDayEntity = createPartakeOrderAggregate.getActivityAccountDayEntity();
        UserRaffleOrderEntity userRaffleOrderEntity = createPartakeOrderAggregate.getUserRaffleOrderEntity();

        // 统一切换路由，以下事务内的所有操作，都走一个路由
        transactionTemplate.execute(status -> {
            try {
                LambdaQueryWrapper<RaffleActivityAccount> accountLambdaQueryWrapper = Wrappers.lambdaQuery();
                LambdaQueryWrapper<RaffleActivityAccountMonth> accountMonthLambdaQueryWrapper = Wrappers.lambdaQuery();
                LambdaQueryWrapper<RaffleActivityAccountDay> accountDayLambdaQueryWrapper = Wrappers.lambdaQuery();
                // 1. 更新总账户
                accountLambdaQueryWrapper.eq(RaffleActivityAccount::getActivityId, activityId)
                        .eq(RaffleActivityAccount::getUserId, userId)
                        .ge(RaffleActivityAccount::getTotalCountSurplus, drawCount);
                int totalCount = raffleActivityAccountMapper.update(RaffleActivityAccount.builder()
                        .totalCountSurplus(activityAccountEntity.getTotalCountSurplus() - drawCount)
                        .updateTime(new Date())
                        .build(), accountLambdaQueryWrapper);


                if (1 != totalCount) {
                    status.setRollbackOnly();
                    log.warn("写入创建参与活动记录，更新总账户额度不足，异常 userId: {} activityId: {}", userId, activityId);
                    throw new AppException(ResponseCode.ACCOUNT_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_QUOTA_ERROR.getInfo());
                }

                // 2. 创建或更新月账户，true - 存在则更新，false - 不存在则插入
                accountMonthLambdaQueryWrapper.eq(RaffleActivityAccountMonth::getActivityId, activityId)
                        .eq(RaffleActivityAccountMonth::getUserId, userId)
                        .eq(RaffleActivityAccountMonth::getMonth, activityAccountMonthEntity.getMonth())
                        .ge(RaffleActivityAccountMonth::getMonthCountSurplus, drawCount);

                if (createPartakeOrderAggregate.isExistAccountMonth()) {
                    int updateMonthCount = raffleActivityAccountMonthMapper.update(RaffleActivityAccountMonth.builder()
                            .monthCountSurplus(activityAccountMonthEntity.getMonthCountSurplus() - drawCount)
                            .updateTime(new Date())
                            .build(), accountMonthLambdaQueryWrapper);

                    if (1 != updateMonthCount) {
                        // 未更新成功则回滚
                        status.setRollbackOnly();
                        log.warn("写入创建参与活动记录，更新月账户额度不足，异常 userId: {} activityId: {} month: {}", userId, activityId, activityAccountMonthEntity.getMonth());
                        throw new AppException(ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getInfo());
                    }
                    // 更新总账户中月镜像库存
                    accountLambdaQueryWrapper.clear();
                    accountLambdaQueryWrapper.eq(RaffleActivityAccount::getActivityId, activityId)
                            .eq(RaffleActivityAccount::getUserId, userId)
                            .ge(RaffleActivityAccount::getMonthCountSurplus, drawCount);
                    raffleActivityAccountMapper.update(RaffleActivityAccount.builder()
                            .monthCountSurplus(activityAccountEntity.getMonthCountSurplus() - drawCount)
                            .updateTime(new Date())
                            .build(), accountLambdaQueryWrapper);

                } else {
                    raffleActivityAccountMonthMapper.insertActivityAccountMonth(RaffleActivityAccountMonth.builder()
                            .userId(activityAccountMonthEntity.getUserId())
                            .activityId(activityAccountMonthEntity.getActivityId())
                            .month(activityAccountMonthEntity.getMonth())
                            .monthCount(activityAccountMonthEntity.getMonthCount())
                            .monthCountSurplus(activityAccountMonthEntity.getMonthCountSurplus() - drawCount)
                            .build());
                    // 新创建月账户，则更新总账表中月镜像额度
                    accountLambdaQueryWrapper.clear();
                    accountLambdaQueryWrapper.eq(RaffleActivityAccount::getActivityId, activityId)
                            .eq(RaffleActivityAccount::getUserId, userId);
                    raffleActivityAccountMapper.update(RaffleActivityAccount.builder()
                            .monthCountSurplus(activityAccountEntity.getMonthCountSurplus() - drawCount)
                            .updateTime(new Date())
                            .build(), accountLambdaQueryWrapper);
                }


                // 3. 创建或更新日账户，true - 存在则更新，false - 不存在则插入
                accountDayLambdaQueryWrapper.eq(RaffleActivityAccountDay::getActivityId, activityId)
                        .eq(RaffleActivityAccountDay::getUserId, userId)
                        .eq(RaffleActivityAccountDay::getDay, activityAccountDayEntity.getDay());

                if (createPartakeOrderAggregate.isExistAccountDay()) {
                    accountDayLambdaQueryWrapper.ge(RaffleActivityAccountDay::getDayCountSurplus, drawCount);
                    int updateDayCount = raffleActivityAccountDayMapper.update(RaffleActivityAccountDay.builder()
                            .dayCountSurplus(activityAccountDayEntity.getDayCountSurplus() - drawCount)
                            .updateTime(new Date())
                            .build(), accountDayLambdaQueryWrapper);
                    if (1 != updateDayCount) {
                        // 未更新成功则回滚
                        status.setRollbackOnly();
                        log.warn("写入创建参与活动记录，更新日账户额度不足，异常 userId: {} activityId: {} day: {}", userId, activityId, activityAccountDayEntity.getDay());
                        throw new AppException(ResponseCode.ACCOUNT_DAY_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_DAY_QUOTA_ERROR.getInfo());
                    }
                    // 更新总账户中日镜像库存
                    accountLambdaQueryWrapper.clear();
                    accountLambdaQueryWrapper.eq(RaffleActivityAccount::getActivityId, activityId)
                            .eq(RaffleActivityAccount::getUserId, userId)
                            .ge(RaffleActivityAccount::getDayCountSurplus, drawCount);
                    raffleActivityAccountMapper.update(RaffleActivityAccount.builder()
                            .dayCountSurplus(activityAccountEntity.getDayCountSurplus() - drawCount)
                            .updateTime(new Date())
                            .build(), accountLambdaQueryWrapper);

                } else {
                    raffleActivityAccountDayMapper.insertActivityAccountDay(RaffleActivityAccountDay.builder()
                            .userId(activityAccountDayEntity.getUserId())
                            .activityId(activityAccountDayEntity.getActivityId())
                            .day(activityAccountDayEntity.getDay())
                            .dayCount(activityAccountDayEntity.getDayCount())
                            .dayCountSurplus(activityAccountDayEntity.getDayCountSurplus() - drawCount)
                            .build());
                    // 新创建日账户，则更新总账表中日镜像额度
                    accountLambdaQueryWrapper.clear();
                    accountLambdaQueryWrapper.eq(RaffleActivityAccount::getActivityId, activityId)
                            .eq(RaffleActivityAccount::getUserId, userId);
                    raffleActivityAccountMapper.update(RaffleActivityAccount.builder()
                            .dayCountSurplus(activityAccountEntity.getDayCountSurplus() - drawCount)
                            .updateTime(new Date())
                            .build(), accountLambdaQueryWrapper);
                }

                // 4. 写入参与活动订单
                String[] OrderIds = userRaffleOrderEntity.getOrderId().split(",");
                List<UserRaffleOrder> userRaffleOrderList = Arrays.stream(OrderIds).map(OrderId -> UserRaffleOrder.builder()
                        .userId(userRaffleOrderEntity.getUserId())
                        .activityId(userRaffleOrderEntity.getActivityId())
                        .activityName(userRaffleOrderEntity.getActivityName())
                        .strategyId(userRaffleOrderEntity.getStrategyId())
                        .orderId(OrderId)
                        .orderTime(userRaffleOrderEntity.getOrderTime())
                        .orderState(userRaffleOrderEntity.getOrderState().getCode())
                        .build()).toList();
                userRaffleOrderMapper.insert(userRaffleOrderList);

                return 1;
            } catch (DuplicateKeyException e) {
                status.setRollbackOnly();
                log.error("写入创建参与活动记录，唯一索引冲突 userId: {} activityId: {}", userId, activityId, e);
                throw new AppException(ResponseCode.INDEX_DUP.getCode(), e);
            }
        });

    }

    public ActivityAccountEntity queryActivityAccountByUserId(String userId, Long activityId) {
        // 1. 查询账户
        RaffleActivityAccount raffleActivityAccount = raffleActivityAccountMapper.selectOne(new LambdaQueryWrapper<RaffleActivityAccount>()
                .eq(RaffleActivityAccount::getUserId, userId)
                .eq(RaffleActivityAccount::getActivityId, activityId));
        if (null == raffleActivityAccount) return null;
        // 2. 转换对象
        return ActivityAccountEntity.builder()
                .userId(raffleActivityAccount.getUserId())
                .activityId(raffleActivityAccount.getActivityId())
                .totalCount(raffleActivityAccount.getTotalCount())
                .totalCountSurplus(raffleActivityAccount.getTotalCountSurplus())
                .dayCount(raffleActivityAccount.getDayCount())
                .dayCountSurplus(raffleActivityAccount.getDayCountSurplus())
                .monthCount(raffleActivityAccount.getMonthCount())
                .monthCountSurplus(raffleActivityAccount.getMonthCountSurplus())
                .build();
    }

    public ActivityAccountMonthEntity queryActivityAccountMonthByUserId(String userId, Long activityId, String month) {
        // 1. 查询账户
        RaffleActivityAccountMonth raffleActivityAccountMonth = raffleActivityAccountMonthMapper.selectOne(new LambdaQueryWrapper<RaffleActivityAccountMonth>()
                .eq(RaffleActivityAccountMonth::getUserId, userId)
                .eq(RaffleActivityAccountMonth::getActivityId, activityId)
                .eq(RaffleActivityAccountMonth::getMonth, month));
        if (null == raffleActivityAccountMonth) return null;
        // 2. 转换对象
        return ActivityAccountMonthEntity.builder()
                .userId(raffleActivityAccountMonth.getUserId())
                .activityId(raffleActivityAccountMonth.getActivityId())
                .month(raffleActivityAccountMonth.getMonth())
                .monthCount(raffleActivityAccountMonth.getMonthCount())
                .monthCountSurplus(raffleActivityAccountMonth.getMonthCountSurplus())
                .build();
    }

    public ActivityAccountDayEntity queryActivityAccountDayByUserId(String userId, Long activityId, String day) {
        // 1. 查询账户
        RaffleActivityAccountDay raffleActivityAccountDay = raffleActivityAccountDayMapper.selectOne(new LambdaQueryWrapper<RaffleActivityAccountDay>()
                .eq(RaffleActivityAccountDay::getUserId, userId)
                .eq(RaffleActivityAccountDay::getActivityId, activityId)
                .eq(RaffleActivityAccountDay::getDay, day));
        if (null == raffleActivityAccountDay) return null;
        // 2. 转换对象
        return ActivityAccountDayEntity.builder()
                .userId(raffleActivityAccountDay.getUserId())
                .activityId(raffleActivityAccountDay.getActivityId())
                .day(raffleActivityAccountDay.getDay())
                .dayCount(raffleActivityAccountDay.getDayCount())
                .dayCountSurplus(raffleActivityAccountDay.getDayCountSurplus())
                .build();

    }

    public List<ActivitySkuEntity> queryActivitySkuListByActivityId(Long activityId) {
        List<RaffleActivitySku> raffleActivitySkus = raffleActivitySkuMapper.selectList(new LambdaQueryWrapper<RaffleActivitySku>()
                .eq(RaffleActivitySku::getActivityId, activityId));
        List<ActivitySkuEntity> activitySkuEntities = new ArrayList<>(raffleActivitySkus.size());
        for (RaffleActivitySku raffleActivitySku : raffleActivitySkus) {
            ActivitySkuEntity activitySkuEntity = new ActivitySkuEntity();
            activitySkuEntity.setSku(raffleActivitySku.getSku());
            activitySkuEntity.setActivityCountId(raffleActivitySku.getActivityCountId());
            activitySkuEntity.setStockCount(raffleActivitySku.getStockCount());
            activitySkuEntity.setStockCountSurplus(raffleActivitySku.getStockCountSurplus());
            activitySkuEntities.add(activitySkuEntity);
        }
        return activitySkuEntities;
    }

    public ActivityCountEntity queryRaffleActivityCountByActivityCountId(Long activityCountId) {
        // 优先从缓存获取
        String cacheKey = Constants.CacheKey.ACTIVITY_COUNT_KEY + activityCountId;
        ActivityCountEntity activityCountEntity = redisService.getValue(cacheKey);
        if (null != activityCountEntity) return activityCountEntity;
        // 从库中获取数据
        RaffleActivityCount raffleActivityCount = raffleActivityCountMapper.selectOne(Wrappers.<RaffleActivityCount>lambdaQuery()
                .eq(RaffleActivityCount::getActivityCountId, activityCountId));
        activityCountEntity = ActivityCountEntity.builder()
                .activityCountId(raffleActivityCount.getActivityCountId())
                .totalCount(raffleActivityCount.getTotalCount())
                .dayCount(raffleActivityCount.getDayCount())
                .monthCount(raffleActivityCount.getMonthCount())
                .build();
        redisService.setValue(cacheKey, activityCountEntity);
        return activityCountEntity;
    }

    public ActivitySkuEntity queryActivitySku(Long sku) {
        RaffleActivitySku raffleActivitySku = raffleActivitySkuMapper.selectOne(new LambdaQueryWrapper<RaffleActivitySku>()
                .eq(RaffleActivitySku::getSku, sku));
        String cacheKey = Constants.CacheKey.ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        Long cacheSkuStock = redisService.getAtomicLong(cacheKey);
        int stockCountSurplus = raffleActivitySku.getStockCountSurplus();
        if (null != cacheSkuStock) {
            stockCountSurplus = cacheSkuStock.intValue();
        }
        return ActivitySkuEntity.builder()
                .sku(raffleActivitySku.getSku())
                .activityId(raffleActivitySku.getActivityId())
                .activityCountId(raffleActivitySku.getActivityCountId())
                .stockCount(raffleActivitySku.getStockCount())
                .stockCountSurplus(stockCountSurplus)
                .productAmount(raffleActivitySku.getProductAmount())
                .build();


    }

    public void cacheActivitySkuStockCount(String cacheKey, Integer stockCount) {
        if (redisService.isExists(cacheKey)) return;
        redisService.setAtomicLong(cacheKey, stockCount);
    }

    public boolean subtractionActivitySkuStock(Long sku, String cacheKey, Date endDateTime) {
        long surplus = redisService.decr(cacheKey);
        if (surplus == 0) {
            // 库存消耗没了以后，发送MQ消息，更新数据库库存
            eventPublisher.publish(activitySkuStockZeroMessageEvent.topic(), activitySkuStockZeroMessageEvent.buildEventMessage(sku));
        } else if (surplus < 0) {
            // 库存小于0，恢复为0个
            redisService.setAtomicLong(cacheKey, 0);
            return false;
        }

        // 1. 按照cacheKey decr 后的值，如 99、98、97 和 key 组成为库存锁的key进行使用。
        // 2. 加锁为了兜底，如果后续有恢复库存，手动处理等【运营是人来操作，会有这种情况发放，系统要做防护】，也不会超卖。因为所有的可用库存key，都被加锁了。
        // 3. 设置加锁时间为活动到期 + 延迟1天
        String lockKey = cacheKey + Constants.UNDERLINE + surplus;
        long expireMillis = endDateTime.getTime() - System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1);
        Boolean lock = redisService.setNx(lockKey, expireMillis, TimeUnit.MILLISECONDS);
        if (!lock) {
            log.info("活动sku库存加锁失败 {}", lockKey);
        }
        return lock;
    }

    public void activitySkuStockConsumeSendQueue(ActivitySkuStockKeyVO activitySkuStockKeyVO) {
        String cacheKey = Constants.CacheKey.ACTIVITY_SKU_COUNT_QUERY_KEY;
        RBlockingQueue<ActivitySkuStockKeyVO> blockingQueue = redisService.getBlockingQueue(cacheKey);
        RDelayedQueue<ActivitySkuStockKeyVO> delayedQueue = redisService.getDelayedQueue(blockingQueue);
        delayedQueue.offer(activitySkuStockKeyVO, 3, TimeUnit.SECONDS);
    }


    public void clearActivitySkuStock(Long sku) {
        raffleActivitySkuMapper.clearActivitySkuStock(sku);
    }


    public Integer queryRaffleActivityAccountDayPartakeCount(Long activityId, String userId) {
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        RaffleActivityAccountDay raffleActivityAccountDay = raffleActivityAccountDayMapper.selectOne(new LambdaQueryWrapper<RaffleActivityAccountDay>()
                .eq(RaffleActivityAccountDay::getActivityId, activityId)
                .eq(RaffleActivityAccountDay::getUserId, userId)
                .eq(RaffleActivityAccountDay::getDay, format));
        // 当日未参与抽奖则为0次
        return raffleActivityAccountDay != null ? raffleActivityAccountDay.getDayCount() - raffleActivityAccountDay.getDayCountSurplus() : 0;
    }

    public ActivityAccountEntity queryActivityAccountEntity(Long activityId, String userId) {
        // 1. 查询总账户额度
        RaffleActivityAccount raffleActivityAccount = raffleActivityAccountMapper.queryActivityAccountByUserId(RaffleActivityAccount.builder()
                .activityId(activityId)
                .userId(userId)
                .build());

        if (null == raffleActivityAccount) {
            return ActivityAccountEntity.builder()
                    .activityId(activityId)
                    .userId(userId)
                    .totalCount(0)
                    .totalCountSurplus(0)
                    .monthCount(0)
                    .monthCountSurplus(0)
                    .dayCount(0)
                    .dayCountSurplus(0)
                    .build();
        }

        // 2. 查询月账户额度
        RaffleActivityAccountMonth raffleActivityAccountMonth = raffleActivityAccountMonthMapper.queryActivityAccountMonthByUserId(RaffleActivityAccountMonth.builder()
                .activityId(activityId)
                .userId(userId)
                .month(dateFormatMonth.format(new Date()))
                .build());

        // 3. 查询日账户额度
        RaffleActivityAccountDay raffleActivityAccountDay = raffleActivityAccountDayMapper.queryActivityAccountDayByUserId(RaffleActivityAccountDay.builder()
                .activityId(activityId)
                .userId(userId)
                .day(dateFormatDay.format(new Date()))
                .build());

        // 组装对象
        ActivityAccountEntity activityAccountEntity = new ActivityAccountEntity();
        activityAccountEntity.setUserId(userId);
        activityAccountEntity.setActivityId(activityId);
        activityAccountEntity.setTotalCount(raffleActivityAccount.getTotalCount());
        activityAccountEntity.setTotalCountSurplus(raffleActivityAccount.getTotalCountSurplus());

        // 如果没有创建日账户，则从总账户中获取日总额度填充。「当新创建日账户时，会获得总账户额度」
        if (null == raffleActivityAccountDay) {
            activityAccountEntity.setDayCount(raffleActivityAccount.getDayCount());
            activityAccountEntity.setDayCountSurplus(raffleActivityAccount.getDayCount());
        } else {
            activityAccountEntity.setDayCount(raffleActivityAccountDay.getDayCount());
            activityAccountEntity.setDayCountSurplus(raffleActivityAccountDay.getDayCountSurplus());
        }

        // 如果没有创建月账户，则从总账户中获取月总额度填充。「当新创建日账户时，会获得总账户额度」
        if (null == raffleActivityAccountMonth) {
            activityAccountEntity.setMonthCount(raffleActivityAccount.getMonthCount());
            activityAccountEntity.setMonthCountSurplus(raffleActivityAccount.getMonthCount());
        } else {
            activityAccountEntity.setMonthCount(raffleActivityAccountMonth.getMonthCount());
            activityAccountEntity.setMonthCountSurplus(raffleActivityAccountMonth.getMonthCountSurplus());
        }

        return activityAccountEntity;
    }

    public Integer queryRaffleActivityAccountPartakeCount(Long activityId, String userId) {
        RaffleActivityAccount raffleActivityAccount = raffleActivityAccountMapper.queryActivityAccountByUserId(RaffleActivityAccount.builder()
                .activityId(activityId)
                .userId(userId)
                .build());
        return raffleActivityAccount.getTotalCount() - raffleActivityAccount.getTotalCountSurplus();
    }

    public void doSaveCreditPayOrder(CreateQuotaOrderAggregate createOrderAggregate) {
        // 创建交易订单
        ActivityOrderEntity activityOrderEntity = createOrderAggregate.getActivityOrderEntity();
        RaffleActivityOrder raffleActivityOrder = new RaffleActivityOrder();
        raffleActivityOrder.setUserId(activityOrderEntity.getUserId());
        raffleActivityOrder.setSku(activityOrderEntity.getSku());
        raffleActivityOrder.setActivityId(activityOrderEntity.getActivityId());
        raffleActivityOrder.setActivityName(activityOrderEntity.getActivityName());
        raffleActivityOrder.setStrategyId(activityOrderEntity.getStrategyId());
        raffleActivityOrder.setOrderId(activityOrderEntity.getOrderId());
        raffleActivityOrder.setOrderTime(activityOrderEntity.getOrderTime());
        raffleActivityOrder.setTotalCount(createOrderAggregate.getTotalCount());
        raffleActivityOrder.setDayCount(createOrderAggregate.getDayCount());
        raffleActivityOrder.setMonthCount(createOrderAggregate.getMonthCount());
        raffleActivityOrder.setPayAmount(activityOrderEntity.getPayAmount());
        raffleActivityOrder.setState(activityOrderEntity.getState().getCode());
        raffleActivityOrder.setOutBusinessNo(activityOrderEntity.getOutBusinessNo());

        // 编程式事务
        transactionTemplate.execute(status -> {
            try {
                raffleActivityOrderMapper.insert(raffleActivityOrder);
                return 1;
            } catch (DuplicateKeyException e) {
                status.setRollbackOnly();
                log.error("写入订单记录，唯一索引冲突 userId: {} activityId: {} sku: {}", activityOrderEntity.getUserId(), activityOrderEntity.getActivityId(), activityOrderEntity.getSku(), e);
                throw new AppException(ResponseCode.INDEX_DUP.getCode(), e);
            }
        });
    }


    public void doSaveNoPayOrder(CreateQuotaOrderAggregate createOrderAggregate) {
        RLock lock = redisService.getLock(Constants.CacheKey.ACTIVITY_ACCOUNT_LOCK + createOrderAggregate.getUserId() + Constants.UNDERLINE + createOrderAggregate.getActivityId());

        try {
            lock.lock(3, TimeUnit.SECONDS);
            // 订单对象
            ActivityOrderEntity activityOrderEntity = createOrderAggregate.getActivityOrderEntity();
            RaffleActivityOrder raffleActivityOrder = new RaffleActivityOrder();
            raffleActivityOrder.setUserId(activityOrderEntity.getUserId());
            raffleActivityOrder.setSku(activityOrderEntity.getSku());
            raffleActivityOrder.setActivityId(activityOrderEntity.getActivityId());
            raffleActivityOrder.setActivityName(activityOrderEntity.getActivityName());
            raffleActivityOrder.setStrategyId(activityOrderEntity.getStrategyId());
            raffleActivityOrder.setOrderId(activityOrderEntity.getOrderId());
            raffleActivityOrder.setOrderTime(activityOrderEntity.getOrderTime());
            raffleActivityOrder.setTotalCount(activityOrderEntity.getTotalCount());
            raffleActivityOrder.setDayCount(activityOrderEntity.getDayCount());
            raffleActivityOrder.setMonthCount(activityOrderEntity.getMonthCount());
            raffleActivityOrder.setTotalCount(createOrderAggregate.getTotalCount());
            raffleActivityOrder.setDayCount(createOrderAggregate.getDayCount());
            raffleActivityOrder.setMonthCount(createOrderAggregate.getMonthCount());
            raffleActivityOrder.setPayAmount(activityOrderEntity.getPayAmount());
            raffleActivityOrder.setState(activityOrderEntity.getState().getCode());
            raffleActivityOrder.setOutBusinessNo(activityOrderEntity.getOutBusinessNo());

            // 账户对象 - 总
            RaffleActivityAccount raffleActivityAccount = new RaffleActivityAccount();
            raffleActivityAccount.setUserId(createOrderAggregate.getUserId());
            raffleActivityAccount.setActivityId(createOrderAggregate.getActivityId());
            raffleActivityAccount.setTotalCount(createOrderAggregate.getTotalCount());
            raffleActivityAccount.setTotalCountSurplus(createOrderAggregate.getTotalCount());
            raffleActivityAccount.setDayCount(createOrderAggregate.getDayCount());
            raffleActivityAccount.setDayCountSurplus(createOrderAggregate.getDayCount());
            raffleActivityAccount.setMonthCount(createOrderAggregate.getMonthCount());
            raffleActivityAccount.setMonthCountSurplus(createOrderAggregate.getMonthCount());

            // 账户对象 - 月
            RaffleActivityAccountMonth raffleActivityAccountMonth = new RaffleActivityAccountMonth();
            raffleActivityAccountMonth.setUserId(createOrderAggregate.getUserId());
            raffleActivityAccountMonth.setActivityId(createOrderAggregate.getActivityId());
            raffleActivityAccountMonth.setMonth(dateFormatMonth.format(new Date()));
            raffleActivityAccountMonth.setMonthCount(createOrderAggregate.getMonthCount());
            raffleActivityAccountMonth.setMonthCountSurplus(createOrderAggregate.getMonthCount());

            // 账户对象 - 日
            RaffleActivityAccountDay raffleActivityAccountDay = new RaffleActivityAccountDay();
            raffleActivityAccountDay.setUserId(createOrderAggregate.getUserId());
            raffleActivityAccountDay.setActivityId(createOrderAggregate.getActivityId());
            raffleActivityAccountDay.setDay(dateFormatDay.format(new Date()));
            raffleActivityAccountDay.setDayCount(createOrderAggregate.getDayCount());
            raffleActivityAccountDay.setDayCountSurplus(createOrderAggregate.getDayCount());


            // 编程式事务
            transactionTemplate.execute(status -> {
                try {
                    // 1. 写入订单
                    raffleActivityOrderMapper.insert(raffleActivityOrder);
                    // 2. 更新账户 - 总
                    RaffleActivityAccount raffleActivityAccountRes = raffleActivityAccountMapper.queryAccountByUserId(raffleActivityAccount);
                    if (null == raffleActivityAccountRes) {
                        raffleActivityAccountMapper.insert(raffleActivityAccount);
                    } else {
                        raffleActivityAccountMapper.updateAccountQuota(raffleActivityAccount);
                    }
                    // 4. 更新账户 - 月
                    raffleActivityAccountMonthMapper.addAccountQuota(raffleActivityAccountMonth);
                    // 5. 更新账户 - 日
                    raffleActivityAccountDayMapper.addAccountQuota(raffleActivityAccountDay);
                    return 1;
                } catch (DuplicateKeyException e) {
                    status.setRollbackOnly();
                    log.error("写入订单记录，唯一索引冲突 userId: {} activityId: {} sku: {}", activityOrderEntity.getUserId(), activityOrderEntity.getActivityId(), activityOrderEntity.getSku(), e);
                    throw new AppException(ResponseCode.INDEX_DUP.getCode(), e);
                }
            });
        } finally {
            lock.unlock();
        }
    }

    public void updateOrder(DeliveryOrderEntity deliveryOrderEntity) {
        RLock lock = redisService.getLock(Constants.CacheKey.ACTIVITY_ACCOUNT_UPDATE_LOCK + deliveryOrderEntity.getUserId());
        try {
            lock.lock(3, TimeUnit.SECONDS);
            // 查询订单
            RaffleActivityOrder raffleActivityOrderReq = new RaffleActivityOrder();
            raffleActivityOrderReq.setUserId(deliveryOrderEntity.getUserId());
            raffleActivityOrderReq.setOutBusinessNo(deliveryOrderEntity.getOutBusinessNo());
            RaffleActivityOrder raffleActivityOrderRes = raffleActivityOrderMapper.queryRaffleActivityOrder(raffleActivityOrderReq);

            // 账户对象 - 总
            RaffleActivityAccount raffleActivityAccount = new RaffleActivityAccount();
            raffleActivityAccount.setUserId(raffleActivityOrderRes.getUserId());
            raffleActivityAccount.setActivityId(raffleActivityOrderRes.getActivityId());
            raffleActivityAccount.setTotalCount(raffleActivityOrderRes.getTotalCount());
            raffleActivityAccount.setTotalCountSurplus(raffleActivityOrderRes.getTotalCount());
            raffleActivityAccount.setDayCount(raffleActivityOrderRes.getDayCount());
            raffleActivityAccount.setDayCountSurplus(raffleActivityOrderRes.getDayCount());
            raffleActivityAccount.setMonthCount(raffleActivityOrderRes.getMonthCount());
            raffleActivityAccount.setMonthCountSurplus(raffleActivityOrderRes.getMonthCount());

            // 账户对象 - 月
            RaffleActivityAccountMonth raffleActivityAccountMonth = new RaffleActivityAccountMonth();
            raffleActivityAccountMonth.setUserId(raffleActivityOrderRes.getUserId());
            raffleActivityAccountMonth.setActivityId(raffleActivityOrderRes.getActivityId());
            raffleActivityAccountMonth.setMonth(dateFormatMonth.format(new Date()));
            raffleActivityAccountMonth.setMonthCount(raffleActivityOrderRes.getMonthCount());
            raffleActivityAccountMonth.setMonthCountSurplus(raffleActivityOrderRes.getMonthCount());

            // 账户对象 - 日
            RaffleActivityAccountDay raffleActivityAccountDay = new RaffleActivityAccountDay();
            raffleActivityAccountDay.setUserId(raffleActivityOrderRes.getUserId());
            raffleActivityAccountDay.setActivityId(raffleActivityOrderRes.getActivityId());
            raffleActivityAccountDay.setDay(dateFormatDay.format(new Date()));
            raffleActivityAccountDay.setDayCount(raffleActivityOrderRes.getDayCount());
            raffleActivityAccountDay.setDayCountSurplus(raffleActivityOrderRes.getDayCount());


            // 编程式事务
            transactionTemplate.execute(status -> {
                try {
                    // 1. 更新订单
                    int updateCount = raffleActivityOrderMapper.updateOrderCompleted(raffleActivityOrderReq);
                    if (1 != updateCount) {
                        status.setRollbackOnly();
                        return 1;
                    }
                    // 2. 更新账户 - 总
                    RaffleActivityAccount raffleActivityAccountRes = raffleActivityAccountMapper.queryAccountByUserId(raffleActivityAccount);
                    if (null == raffleActivityAccountRes) {
                        raffleActivityAccountMapper.insert(raffleActivityAccount);
                    } else {
                        raffleActivityAccountMapper.updateAccountQuota(raffleActivityAccount);
                    }
                    // 4. 更新账户 - 月
                    raffleActivityAccountMonthMapper.addAccountQuota(raffleActivityAccountMonth);
                    // 5. 更新账户 - 日
                    raffleActivityAccountDayMapper.addAccountQuota(raffleActivityAccountDay);
                    return 1;
                } catch (DuplicateKeyException e) {
                    status.setRollbackOnly();
                    log.error("更新订单记录，完成态，唯一索引冲突 userId: {} outBusinessNo: {}", deliveryOrderEntity.getUserId(), deliveryOrderEntity.getOutBusinessNo(), e);
                    throw new AppException(ResponseCode.INDEX_DUP.getCode(), e);
                }
            });
        } finally {
            lock.unlock();
        }
    }

    public List<SkuProductEntity> querySkuProductEntityListByActivityId(Long activityId) {
        List<RaffleActivitySku> raffleActivitySkus = raffleActivitySkuMapper.selectList(Wrappers.<RaffleActivitySku>
                lambdaQuery().eq(RaffleActivitySku::getActivityId, activityId));
        LambdaQueryWrapper<RaffleActivityCount> lambdaQueryWrapper = Wrappers.lambdaQuery();
        return raffleActivitySkus.stream().map(raffleActivitySku -> {
            RaffleActivityCount raffleActivityCount = raffleActivityCountMapper.selectOne(lambdaQueryWrapper
                    .eq(RaffleActivityCount::getActivityCountId, raffleActivitySku.getActivityCountId()));
            SkuProductEntity.ActivityCount activityCount = new SkuProductEntity.ActivityCount();
            activityCount.setTotalCount(raffleActivityCount.getTotalCount());
            activityCount.setMonthCount(raffleActivityCount.getMonthCount());
            activityCount.setDayCount(raffleActivityCount.getDayCount());
            lambdaQueryWrapper.clear();
            return SkuProductEntity.builder()
                    .sku(raffleActivitySku.getSku())
                    .activityId(raffleActivitySku.getActivityId())
                    .activityCountId(raffleActivitySku.getActivityCountId())
                    .stockCount(raffleActivitySku.getStockCount())
                    .stockCountSurplus(raffleActivitySku.getStockCountSurplus())
                    .productAmount(raffleActivitySku.getProductAmount())
                    .activityCount(activityCount)
                    .build();
        }).toList();
    }

    public UnpaidActivityOrderEntity queryUnpaidActivityOrder(SkuRechargeEntity skuRechargeEntity) {
        RaffleActivityOrder raffleActivityOrderReq = new RaffleActivityOrder();
        raffleActivityOrderReq.setUserId(skuRechargeEntity.getUserId());
        raffleActivityOrderReq.setSku(skuRechargeEntity.getSku());
        RaffleActivityOrder raffleActivityOrderRes = raffleActivityOrderMapper.queryUnpaidActivityOrder(raffleActivityOrderReq);
        if (null == raffleActivityOrderRes) return null;
        return UnpaidActivityOrderEntity.builder()
                .userId(raffleActivityOrderRes.getUserId())
                .orderId(raffleActivityOrderRes.getOrderId())
                .outBusinessNo(raffleActivityOrderRes.getOutBusinessNo())
                .payAmount(raffleActivityOrderRes.getPayAmount())
                .build();
    }


    public void calendarSignRebate(DeliveryOrderEntity deliveryOrderEntity) {

        // 账户对象 - 总
        RaffleActivityAccount raffleActivityAccount = new RaffleActivityAccount();
        raffleActivityAccount.setUserId(deliveryOrderEntity.getUserId());
        raffleActivityAccount.setActivityId(deliveryOrderEntity.getActivityId());
        raffleActivityAccount.setTotalCount(1);
        raffleActivityAccount.setTotalCountSurplus(1);
        raffleActivityAccount.setDayCount(1);
        raffleActivityAccount.setDayCountSurplus(1);
        raffleActivityAccount.setMonthCount(1);
        raffleActivityAccount.setMonthCountSurplus(1);

        // 账户对象 - 月
        RaffleActivityAccountMonth raffleActivityAccountMonth = new RaffleActivityAccountMonth();
        raffleActivityAccountMonth.setUserId(deliveryOrderEntity.getUserId());
        raffleActivityAccountMonth.setActivityId(deliveryOrderEntity.getActivityId());
        raffleActivityAccountMonth.setMonth(dateFormatMonth.format(new Date()));
        raffleActivityAccountMonth.setMonthCount(1);
        raffleActivityAccountMonth.setMonthCountSurplus(1);

        // 账户对象 - 日
        RaffleActivityAccountDay raffleActivityAccountDay = new RaffleActivityAccountDay();
        raffleActivityAccountDay.setUserId(deliveryOrderEntity.getUserId());
        raffleActivityAccountDay.setActivityId(deliveryOrderEntity.getActivityId());
        raffleActivityAccountDay.setDay(dateFormatDay.format(new Date()));
        raffleActivityAccountDay.setDayCount(1);
        raffleActivityAccountDay.setDayCountSurplus(1);

        // 编程式事务
        transactionTemplate.execute(status -> {
            try {
                //  更新账户 - 总
                RaffleActivityAccount raffleActivityAccountRes = raffleActivityAccountMapper.queryAccountByUserId(raffleActivityAccount);
                if (null == raffleActivityAccountRes) {
                    raffleActivityAccountMapper.insert(raffleActivityAccount);
                } else {
                    raffleActivityAccountMapper.updateAccountQuota(raffleActivityAccount);
                }
                //  更新账户 - 月
                raffleActivityAccountMonthMapper.addAccountQuota(raffleActivityAccountMonth);
                // 更新账户 - 日
                raffleActivityAccountDayMapper.addAccountQuota(raffleActivityAccountDay);
                return 1;
            } catch (Exception e) {
                status.setRollbackOnly();
                log.error("签到失败， userId: {} activityId: {} ", deliveryOrderEntity.getUserId(), deliveryOrderEntity.getActivityId());
                throw new AppException(ResponseCode.INDEX_DUP.getCode(), e);
            }
        });

    }

    public ActivitySkuStockKeyVO takeQueueValue() {
        String cacheKey = Constants.CacheKey.ACTIVITY_SKU_COUNT_QUERY_KEY;
        RBlockingQueue<ActivitySkuStockKeyVO> destinationQueue = redisService.getBlockingQueue(cacheKey);
        return destinationQueue.poll();
    }

    public void updateActivitySkuStock(Long sku) {
        raffleActivitySkuMapper.updateActivitySkuStock(sku);
    }

    public void clearQueueValue() {
        String cacheKey = Constants.CacheKey.ACTIVITY_SKU_COUNT_QUERY_KEY;
        RBlockingQueue<ActivitySkuStockKeyVO> destinationQueue = redisService.getBlockingQueue(cacheKey);
        destinationQueue.clear();
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public void alterActivityState(Long activityId, String currState, String endState) {
        raffleActivityStageMapper.alterActivityStage(activityId, currState, endState);
        raffleActivityMapper.alterActivityStateByActivityId(activityId, currState, endState);
    }

    public void appendStageActivity(String channel, String source, Long activityId) {
        RaffleActivityStage raffleActivityStage = new RaffleActivityStage();
        raffleActivityStage.setChannel(channel);
        raffleActivityStage.setSource(source);
        raffleActivityStage.setActivityId(activityId);
        raffleActivityStageMapper.insert(raffleActivityStage);
    }

    public Long queryStageActiveBySC(String channel, String source) {
        RaffleActivityStage raffleActivityStage = new RaffleActivityStage();
        raffleActivityStage.setChannel(channel);
        raffleActivityStage.setSource(source);
        return raffleActivityStageMapper.queryStageActiveBySC(raffleActivityStage);
    }

    public List<RaffleActivityStageEntity> queryStageActivityList() {
        List<RaffleActivityStageEntity> raffleActivityStageEntities = new ArrayList<>();
        List<RaffleActivityStage> list = raffleActivityStageMapper.queryStageActivityList();
        for (RaffleActivityStage raffleActivityStage : list) {
            RaffleActivityStageEntity raffleActivityStageEntity = RaffleActivityStageEntity.builder()
                    .id(raffleActivityStage.getId())
                    .channel(raffleActivityStage.getChannel())
                    .source(raffleActivityStage.getSource())
                    .activityId(raffleActivityStage.getActivityId())
                    .state(raffleActivityStage.getState())
                    .build();
            raffleActivityStageEntities.add(raffleActivityStageEntity);
        }
        return raffleActivityStageEntities;
    }

    public Long queryStageActivity2ActiveById(Long id) {
        return raffleActivityStageMapper.selectById(id).getActivityId();
    }

    public String queryCurrActivityState(Long activityId) {
       return raffleActivityStageMapper.queryCurrActivityState(activityId);
    }
}
